import { traceWarn } from "../../logging";
import { EQEnvKind } from "../base/info";
import { isCondaEnvironment } from "./environmentManagers/conda";
import { isGloballyInstalledEnv } from "./environmentManagers/globalInstalledEnvs";
import { getPrioritizedEnvKinds } from '../base/info/envKind';

function getIdentifiers(): Map<EQEnvKind, (path: string) => Promise<boolean>> {
    const notImplemented = () => Promise.resolve(false);
    const defaultTrue = () => Promise.resolve(true);
    const identifier: Map<EQEnvKind, (path: string) => Promise<boolean>> = new Map();
    Object.values(EQEnvKind).forEach((k) => {
        identifier.set(k, notImplemented);
    });

    identifier.set(EQEnvKind.Conda, isCondaEnvironment);
    identifier.set(EQEnvKind.Unknown, defaultTrue);
    identifier.set(EQEnvKind.OtherGlobal, isGloballyInstalledEnv);
    return identifier;
}


export async function identifyEnvironment(path: string): Promise<EQEnvKind> {
    const identifiers = getIdentifiers();
    const prioritizedEnvTypes = getPrioritizedEnvKinds();
    for (const e of prioritizedEnvTypes) {
        const identifier = identifiers.get(e);
        if (
            identifier &&
            (await identifier(path).catch((ex) => {
                traceWarn(`Identifier for ${e} failed to identify ${path}`, ex);
                return false;
            }))
        ) {
            return e;
        }
    }
    return EQEnvKind.Unknown;
}